package org.dromara.netbar.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.dromara.common.core.constant.SystemConstants;
import org.dromara.common.core.utils.AssertUtils;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.RedisKeyGeneratorUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.redis.utils.RedisUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.domain.SysRole;
import org.springframework.stereotype.Service;
import org.dromara.netbar.domain.bo.NetbarMemberLevelBo;
import org.dromara.netbar.domain.vo.NetbarMemberLevelVo;
import org.dromara.netbar.domain.NetbarMemberLevel;
import org.dromara.netbar.mapper.NetbarMemberLevelMapper;
import org.dromara.netbar.service.INetbarMemberLevelService;

import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 会员等级管理Service业务层处理
 *
 * @author Lion Li
 * @date 2025-06-29
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class NetbarMemberLevelServiceImpl implements INetbarMemberLevelService {

    private final NetbarMemberLevelMapper baseMapper;

    /**
     * 查询会员等级管理
     *
     * @param levelId 主键
     * @return 会员等级管理
     */
    @Override
    public NetbarMemberLevelVo queryById(Long levelId){
        return baseMapper.selectVoById(levelId);
    }

    /**
     * 分页查询会员等级管理列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 会员等级管理分页列表
     */
    @Override
    public TableDataInfo<NetbarMemberLevelVo> queryPageList(NetbarMemberLevelBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<NetbarMemberLevel> lqw = buildQueryWrapper(bo);
        Page<NetbarMemberLevelVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的会员等级管理列表
     *
     * @param bo 查询条件
     * @return 会员等级管理列表
     */
    @Override
    public List<NetbarMemberLevelVo> queryList(NetbarMemberLevelBo bo) {
        LambdaQueryWrapper<NetbarMemberLevel> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<NetbarMemberLevel> buildQueryWrapper(NetbarMemberLevelBo bo) {
        LambdaQueryWrapper<NetbarMemberLevel> lqw = Wrappers.lambdaQuery();
        lqw.orderByAsc(NetbarMemberLevel::getLevelId);
        lqw.like(StringUtils.isNotBlank(bo.getLevelName()), NetbarMemberLevel::getLevelName, bo.getLevelName());
        return lqw;
    }

    /**
     * 新增会员等级管理
     *
     * @param bo 会员等级管理
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(NetbarMemberLevelBo bo) {
        NetbarMemberLevel add = MapstructUtils.convert(bo, NetbarMemberLevel.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setLevelId(add.getLevelId());
        }
        String key = LoginHelper.getTenantId() + ":seatTypeKeys";
        RedisUtils.deleteObject(key);
        return flag;
    }

    /**
     * 修改会员等级管理
     *
     * @param bo 会员等级管理
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(NetbarMemberLevelBo bo) {
        NetbarMemberLevel update = MapstructUtils.convert(bo, NetbarMemberLevel.class);
        validEntityBeforeSave(update);
        boolean b = baseMapper.updateById(update) > 0;
        String key = LoginHelper.getTenantId() + ":seatTypeKeys";
        RedisUtils.deleteObject(key);
        return b;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(NetbarMemberLevel entity){
        //TODO 做一些数据校验,如唯一约束
        AssertUtils.notNull(entity, "请输入会员等级信息");
        AssertUtils.notNull(entity.getLevelName(), "请输入会员等级名称");
    }

    /**
     * 校验并批量删除会员等级管理信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public List<NetbarMemberLevelVo> listMemberLevelByIds(List<Long> memberLevelIds) {
        return baseMapper.selectVoList(new QueryWrapper<NetbarMemberLevel>()
            .in(CollUtil.isNotEmpty(memberLevelIds), "level_id", memberLevelIds));
    }

    @Override
    public Map<String, Long> getLevelNameIdMap(String tenantId) {
        String key = tenantId+ ":seatTypeKeys";
        if (RedisUtils.hasKey(key)) {
            return RedisUtils.getCacheObject(key);
        }
        // 获取会员名称和id
        List<NetbarMemberLevelVo> netbarMemberLevelVos = baseMapper.selectVoList(new LambdaQueryWrapper<NetbarMemberLevel>().select(NetbarMemberLevel::getLevelName, NetbarMemberLevel::getLevelId));
        Map<String, Long> levelNameIdMap = new LinkedHashMap<>();
        for (NetbarMemberLevelVo netbarMemberLevelVo : netbarMemberLevelVos) {
            levelNameIdMap.put(netbarMemberLevelVo.getLevelName(), netbarMemberLevelVo.getLevelId());
        }
        RedisUtils.setCacheObject(key, levelNameIdMap, Duration.ofHours(1));
        return levelNameIdMap;
    }

    /**
     * // 25-07-18 根据租户Id，is_auto_upgrade = 'Y',min_recharge 降序， min_recharge小于balance的第一条 获取数据
     * @param tenantId 租户Id
     * @param balance 余额 (分)
     */
    @Override
    public NetbarMemberLevelVo getMemberLevelByAutoBalance(String tenantId, Long balance) {
        LambdaQueryWrapper<NetbarMemberLevel> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(NetbarMemberLevel::getTenantId, tenantId)
            .eq(NetbarMemberLevel::getIsAutoUpgrade, "Y").orderByDesc(NetbarMemberLevel::getMinRecharge);
        lambdaQueryWrapper.le(NetbarMemberLevel::getMinRecharge, balance/100);
        List<NetbarMemberLevelVo> netbarMemberLevelVos = baseMapper.selectVoList(lambdaQueryWrapper);
        if (CollUtil.isNotEmpty(netbarMemberLevelVos)) {
            return netbarMemberLevelVos.get(0);
        }
        return null;
    }

    @Override
    public boolean compareMemberLevelAmount(Long oldMemberLevelId, Long newMemberLevelId) {
        if (null == oldMemberLevelId) {
            return true;
        }
        if (null == newMemberLevelId) {
            return false;
        }
        NetbarMemberLevelVo oldMemberLevel = baseMapper.selectVoOne(new LambdaQueryWrapper<NetbarMemberLevel>().eq(NetbarMemberLevel::getLevelId, oldMemberLevelId));
        NetbarMemberLevelVo newMemberLevel = baseMapper.selectVoOne(new LambdaQueryWrapper<NetbarMemberLevel>().eq(NetbarMemberLevel::getLevelId, newMemberLevelId));
        if (null != oldMemberLevel && null != newMemberLevel){
            return oldMemberLevel.getMinRecharge().compareTo(newMemberLevel.getMinRecharge()) < 0;
        }
        return false;
    }

    @Override
    public String getMemberLevelNameByLevelId(Long memberLevelId) {
        String memberLevelKey = RedisKeyGeneratorUtils.getMemberLevelKey(LoginHelper.getTenantId());
        if (!RedisUtils.hasKey(memberLevelKey)) {
            NetbarMemberLevelVo memberLevelVo = RedisUtils.getCacheMapValue(memberLevelKey, String.valueOf(memberLevelId));
            return memberLevelVo.getLevelName();
        }
        NetbarMemberLevelVo netbarMemberLevelVo = baseMapper.selectVoOne(new LambdaQueryWrapper<NetbarMemberLevel>().eq(NetbarMemberLevel::getLevelId, memberLevelId));
        if (null != netbarMemberLevelVo) {
            RedisUtils.setCacheMapValue(memberLevelKey, String.valueOf(memberLevelId), netbarMemberLevelVo);
            return netbarMemberLevelVo.getLevelName();
        }
        return null;
    }
}
